use core::future::Future;

pub trait Service<Request> {
    type Response;
    type Error;
    // Future 类型受 Future trait 约束
    type Future: Future;
}

pub trait Formatter {
    fn format(&self, input: &mut String) -> bool;
}

struct MarkdownFormatter;
impl Formatter for MarkdownFormatter {
    fn format(&self, input: &mut String) -> bool {
        input.push_str("\nformatted with Markdown formatter");
        true
    }
}

struct RustFormatter{
    pub name:String,
    pub age:u32,
}
impl RustFormatter{
    pub fn new()->Self{
        RustFormatter{name:"abc".to_string(),age:1234}
    }
}
impl Formatter for RustFormatter {
    fn format(&self, input: &mut String) -> bool {
        input.push_str("\nformatted with Rust formatter");
        true
    }
}

struct HtmlFormatter;
impl Formatter for HtmlFormatter {
    fn format(&self, input: &mut String) -> bool {
        input.push_str("\nformatted with HTML formatter");
        true
    }
}

pub fn format(input: &mut String, formatters: Vec<&dyn Formatter>) {
    for formatter in formatters {
        formatter.format(input);
    }
}
#[test]
fn test_main() {
    let mut text = "Hello world!".to_string();
    let html: &dyn Formatter = &HtmlFormatter;
    let rust: &dyn Formatter = &RustFormatter{name:"abc".to_string(),age:123,};
    let formatters = vec![html, rust];
    format(&mut text, formatters);
    println!("text: {}", text);
    println!("rust trait object: {:p}", rust);
    println!("html trait object: {:p}", html);
    let hf=&HtmlFormatter;
    let rf=&RustFormatter::new();
    println!("rust struct object: {:p}", &rf);
    println!("html struct object: {:p}", &hf);

}

#[test]
fn test_check() {
    use std::{fs::File, io::Write};
    let mut f = File::create("/tmp/test_write_trait").unwrap();
    let w: &mut dyn Write = &mut f;
    w.write_all(b"hello ").unwrap();
    // let w1 = w.by_ref(); //
    w.write_all(b"world").unwrap();
}

#[derive(Debug)]
struct SentenceIter<'a> {
    s: &'a mut &'a str,
    delimiter: char,
}

impl<'a> SentenceIter<'a> {
    pub fn new(s: &'a mut &'a str, delimiter: char) -> Self {
        Self { s, delimiter }
    }
}

impl<'a> Iterator for SentenceIter<'a> {
    type Item = &'a str; // 想想 Item 应该是什么类型？
    fn next(&mut self) -> Option<Self::Item> {
        // 如何实现 next 方法让下面的测试通过？
        if let Some(index) = self.s.find(self.delimiter) {
            let delimiter_len=self.delimiter.len_utf8();
            let s1=&self.s[..index+delimiter_len];
            let remain=&self.s[index+delimiter_len..];
            *self.s= remain.trim(); //修改指针 'a生命周期，前半截的也不会丢失。
            return Some(s1);
        } else {
            None
        }
    }
}

#[test]
fn it_works() {
    let mut s = "This is the 1st sentence. This is the 2nd sentence.";
    {
        let mut iter = SentenceIter::new(&mut s, '.'); // mutable borrow occurs here
        assert_eq!(iter.next(), Some("This is the 1st sentence."));
        assert_eq!(iter.next(), Some("This is the 2nd sentence."));
        assert_eq!(iter.next(), None);
        println!("{:?}", &iter);
    } //并没有概括s的生命周期。所以下面的borrow不可以。
    // println!("{:?}",&s); //immutable borrow occurs here
}
#[test]
fn test_iter() {
    let mut s = "a。 b。 c";
    let sentences: Vec<_> = SentenceIter::new(&mut s, '。').collect();
    println!("sentences: {:?}", sentences);
}



use std::fmt::{Debug, Display};
use std::mem::transmute;
#[test]
fn test_print_vtables() {

    let s2 = String::from("goodbye world!");
    let s1 = String::from("hello world!");
    // Display / Debug trait object for s
    let w1: &dyn Display = &s1;
    let w2: &dyn Debug = &s1;

    // Display / Debug trait object for s1
    let w3: &dyn Display = &s2;
    let w4: &dyn Debug = &s2;

    // 强行把 triat object 转换成两个地址 (usize, usize)
    // 这是不安全的，所以是 unsafe
    let (addr1, vtable1): (usize, usize) = unsafe { transmute(w1) };
    let (addr2, vtable2): (usize, usize) = unsafe { transmute(w2) };
    let (addr3, vtable3): (usize, usize) = unsafe { transmute(w3) };
    let (addr4, vtable4): (usize, usize) = unsafe { transmute(w4) };

    // s 和 s1 在栈上的地址，以及 main 在 TEXT 段的地址
    println!(
        "s1: {:p}, s2: {:p}, main(): {:p}",
        &s1, &s2, test_print_vtables as *const ()
    );
    // trait object(s / Display) 的 ptr 地址和 vtable 地址
    println!("addr1: 0x{:x}, vtable1: 0x{:x}", addr1, vtable1);
    // trait object(s / Debug) 的 ptr 地址和 vtable 地址
    println!("addr2: 0x{:x}, vtable2: 0x{:x}", addr2, vtable2);

    // trait object(s1 / Display) 的 ptr 地址和 vtable 地址
    println!("addr3: 0x{:x}, vtable3: 0x{:x}", addr3, vtable3);

    // trait object(s1 / Display) 的 ptr 地址和 vtable 地址
    println!("addr4: 0x{:x}, vtable4: 0x{:x}", addr4, vtable4);

    // 指向同一个数据的 trait object 其 ptr 地址相同
    assert_eq!(addr1, addr2);
    assert_eq!(addr3, addr4);

    // 指向同一种类型的同一个 trait 的 vtable 地址相同
    // 这里都是 String + Display
    assert_eq!(vtable1, vtable3);
    // 这里都是 String + Debug
    assert_eq!(vtable2, vtable4);

}

#[derive(Debug)]
struct Foo;

trait Bar{
    fn baz(&self);
}

impl Bar for Foo{
    fn baz(&self) { println!("{:?}",self)}
}

fn static_dispatch<T>(t: &T) where T:Bar{
    t.baz();
}

//为什么这里是动态分发就无法确定类型大小
//这里t也是限制为&Bar对象呀..
//answer: 编译不通过,必须指定为trait obj的如果限制为trait时
fn dynamic_dispatch(t: &dyn Bar){
    t.baz();
}
#[test]
fn test_foo(){
    let f=Foo;
    dynamic_dispatch(&f);
}



#[derive(Clone, Debug)]
struct Developer {
    name: String,
    age: u8,
    lang: Language
}

#[allow(dead_code)]
#[derive(Clone, Debug)]
enum Language {
    Rust,
    TypeScript,
    Elixir,
    Haskell
}
#[test]
fn test_clone() {
    let dev = Developer {
        name: "Tyr".to_string(),
        age: 18,
        lang: Language::Rust
    };
    let dev1 = dev.clone();
    println!("dev: {:?}, addr of dev name: {:p}", dev, dev.name.as_str());
    println!("dev1: {:?}, addr of dev1 name: {:p}", dev1, dev1.name.as_str())
}




use std::{fmt, slice, thread};
use std::rc::Rc;
use std::cell::RefCell;

// 注意这里，我们实现了 Copy，这是因为 *mut u8/usize 都支持 Copy
#[derive(Clone, Copy)]
struct RawBuffer {
    // 裸指针用 *const / *mut 来表述，这和引用的 & 不同
    ptr: *mut u8,
    len: usize,
}

impl From<Vec<u8>> for RawBuffer {
    fn from(vec: Vec<u8>) -> Self {
        let slice = vec.into_boxed_slice();
        Self {
            len: slice.len(),
            // into_raw 之后，Box 就不管这块内存的释放了，RawBuffer 需要处理释放
            ptr: Box::into_raw(slice) as *mut u8,
        }
    }
}

// 如果 RawBuffer 实现了 Drop trait，就可以在所有者退出时释放堆内存
// 然后，Drop trait 会跟 Copy trait 冲突，要么不实现 Copy，要么不实现 Drop
// 如果不实现 Drop，那么就会导致内存泄漏，但它不会对正确性有任何破坏
// 比如不会出现 use after free 这样的问题。
// 你可以试着把下面注释去掉，看看会出什么问题
// impl Drop for RawBuffer {
//     #[inline]
//     fn drop(&mut self) {
//         let data = unsafe { Box::from_raw(slice::from_raw_parts_mut(self.ptr, self.len)) };
//         drop(data)
//     }
// }

impl fmt::Debug for RawBuffer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let data = self.as_ref();
        write!(f, "{:p}: {:?}", self.ptr, data)
    }
}

impl AsRef<[u8]> for RawBuffer {
    fn as_ref(&self) -> &[u8] {
        unsafe { slice::from_raw_parts(self.ptr, self.len) }
    }
}
#[test]
fn test_copy_drop_not_occur_simultaneously() {
    let data = vec![1, 2, 3, 4];

    let buf: RawBuffer = data.into();

    // 因为 buf 允许 Copy，所以这里 Copy 了一份
    use_buffer(buf);

    // buf 还能用
    println!("buf: {:?}", buf);
}

fn use_buffer(buf: RawBuffer) {
    println!("buf to die: {:?}", buf);

    // 这里不用特意 drop，写出来只是为了说明 Copy 出来的 buf 被 Drop 了
    drop(buf)
}



// Rc 既不是 Send，也不是 Sync
#[test]
fn rc_is_not_send_and_sync() {
    let a = Rc::new(1);
    let b = a.clone();
    let c = a.clone();
    // the trait `Send` is not implemented for `Rc<i32>`   required by a bound in `spawn`
    // thread::spawn(move || {
    //     println!("c= {:?}", c);
    // });
}

#[test]
fn refcell_is_send() {
    let b=1;
    let a = RefCell::new(b);
    thread::spawn(move || {
        println!("a= {:?}", a);
    });
    println!("{:?}",b);
}
